import java.awt.AWTException;
import java.io.*;
import java.util.*;

public class FileProcessor implements HttpProcessor{
	static int x, y;
	private HttpInputStream req;
	private String resource = "";
	public FileProcessor(HttpInputStream req) {
		this.req = req;
	}
	public void process(HttpOutputStream hos) throws IOException {
		byte[] buf = new byte[256];
		int len = 0;
		FileInputStream fis = null;
		
		try {
			fis = new FileInputStream(new File(req.getResourcePath()));
			System.out.println(req.getResourcePath());
		} catch(IOException ioe) {
			fis = new FileInputStream(new File(HTTPconf.getResourcePath("/"+HTTPconf.notFoundFile)));
			/*
			hos.setCode(400);
			hos.setHeader("Server", HTTPconf.serverName);
			hos.setHeader("Content-type", HTTPconf.getMime(req.getResourcePath()));
			hos.write(buf, 0, 30);
			hos.close();
			return;
			*/
		}
		try {
			hos.setCode(200);
			hos.setHeader("Server", HTTPconf.serverName);
			hos.setHeader("Content-type", HTTPconf.getMime(req.getResourcePath()));
			
			Hashtable query = req.getQueryString();
			Enumeration keys = query.keys();
			
			
			String differ = null;
			if(HTTPconf.controlFile != null){
				differ = "/"+HTTPconf.controlFile;
			}

			if(req.getFileName().equals(differ)){
			while(keys.hasMoreElements()) {
				String key = (String)keys.nextElement();
				String value = (String)query.get(key);
				System.out.println("\t"+key+"="+value+"<br/>");
				if(key.equals("x"))
					x = Integer.parseInt(value);
				if(key.equals("y"))
					y = Integer.parseInt(value);
			}
			try{
			ServerControl serverControl = new ServerControl();
			serverControl.setMouseMove(x, y);
			serverControl = null;
			} catch (AWTException awte) {
				awte.printStackTrace();
			}
			
			ServerCapture serverCapture = new ServerCapture();
			serverCapture.capture(HTTPconf.homeDir.toString(), "nice",ServerCapture.IMG_FORMAT_JPG);
			serverCapture = null;
			
			}
			
			while( (len=fis.read(buf)) != -1) {
				hos.write(buf, 0, len);
			}
			fis.close();
			hos.close();
		} catch(IOException ioe) {
			ioe.printStackTrace();
		} catch(NullPointerException npe) {
			npe.printStackTrace();
		}
	}
	
	public void print(String s) {
		resource += s;
	}
}
